package com.ykun.springboot.service;

import com.github.pagehelper.PageHelper;
import com.ykun.springboot.mapper.CountryMap;
import com.ykun.springboot.model.Country;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Created by yangkun on 2017/7/30.
 */
@Service
public class CountryService {

    @Autowired
    private CountryMap countryMapper;


    public List<Country> getAll(Country country) {
        Example example = new Example(Country.class);
        if(country.getPage() != null && country.getRows() != null){
            PageHelper.startPage(country.getPage(), country.getRows());
        }
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(country.getCountryname())){
            criteria.andLike("countryname", "%" + country.getCountryname() + "%");
        }
        if(StringUtils.isNotBlank(country.getCountrycode())){
            criteria.andLike("countrycode", "%" + country.getCountrycode() + "%");
        }
        return countryMapper.selectByExample(example);
    }

    public Country getById(Integer id) {
        return countryMapper.selectByPrimaryKey(id);
    }

    public void deleteById(Integer id) {
        countryMapper.deleteByPrimaryKey(id);
    }

    public void saveOrUpdate(Country country) {
        if(country.getId() == null){
            countryMapper.insert(country);
        }else{
            countryMapper.updateByPrimaryKey(country);
        }
    }
}
